# -*- coding: utf-8 -*-
"""
完整的Agent发布流程（包含配置）
"""

import os
import sys
import json
from pathlib import Path
from dotenv import load_dotenv

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# 加载环境变量
load_dotenv(project_root / '.env')

from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig
from scripts.auto_publish_agent import AgentAutoPublisher


def get_app_config_draft(client, workspace_id, app_id):
    """获取Agent草稿配置"""
    print("[配置] 获取Agent草稿配置...")

    result = client.make_request(
        action="GetAppConfigDraft",
        body={
            "WorkspaceID": workspace_id,
            "AppID": app_id,
            "Top": {}
        }
    )

    if "Response" in result:
        if result.get("Response", {}).get("Error"):
            error = result["Response"]["Error"]
            raise Exception(f"获取配置失败: {error.get('Code')} - {error.get('Message')}")
        return result["Response"]
    else:
        return result


def main():
    """完整发布流程"""

    # 已存在的AppID
    app_id = "d3rincoiqq79p3439na0"

    print("=" * 80)
    print(f"完整发布流程测试: {app_id}")
    print("=" * 80)

    client = HiAgentAPIClient()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID

    try:
        # 1. 获取草稿配置
        config_draft = get_app_config_draft(client, workspace_id, app_id)
        print(f"[成功] 获取到配置")
        print(f"  AgentMode: {config_draft.get('AgentMode', 'Single')}")

        # 2. 创建 Publisher
        publisher = AgentAutoPublisher()
        publisher.app_id = app_id

        # 3. 创建API密钥
        print("\n[步骤1] 创建API密钥...")
        publisher.create_api_key(name=f"发布API密钥-{app_id[-6:]}")

        # 4. 发布（传递配置）
        print("\n[步骤2] 发布到智能体中心...")

        # 构建发布请求
        publish_request = {
            "WorkspaceID": workspace_id,
            "AppID": app_id,
            "Version": "1.0.1",
            "VersionDescription": "完整配置发布测试",
            "AgentMode": config_draft.get("AgentMode", "Single"),
            "PublishAppCenter": {
                "IsPublish": True,
                "AuthType": "Public",
                "CategoryCodeList": ["WorkAssistant"],
                "AuthRangeType": "All"
            },
            "Top": {}
        }

        # 根据 AgentMode 添加配置
        agent_mode = config_draft.get("AgentMode", "Single")
        if agent_mode == "Single":
            publish_request["AppConfig"] = config_draft.get("AppConfig", {})
        elif agent_mode == "Multi":
            publish_request["MultiAgentConfigInfo"] = config_draft.get("MultiAgentConfig", {})

        print(f"\n[DEBUG] 发布请求:\n{json.dumps(publish_request, indent=2, ensure_ascii=False)}\n")

        result = client.make_request(
            action="PublishApp",
            body=publish_request
        )

        print(f"\n[DEBUG] 发布响应:\n{result}\n")

        # 5. 检查结果
        if "Response" in result:
            response = result["Response"]
        else:
            response = result

        publish_id = response.get("PublishID")
        print(f"[成功] PublishID: {publish_id}")

        if publish_id:
            publisher.publish_id = publish_id

            # 6. 自动审批
            print("\n[步骤3] 自动审批...")
            import time
            time.sleep(2)
            publisher.auto_approve()

            # 7. 开启API
            print("\n[步骤4] 开启API访问...")
            publisher.enable_api_access(enable=True)

            # 8. 检查状态
            print("\n[步骤5] 检查发布状态...")
            time.sleep(3)  # 等待发布完成
            publisher.check_publish_status()

            print("\n" + "=" * 80)
            print("发布成功！")
            print("=" * 80)
            print(f"AppID: {app_id}")
            print(f"API Key: {publisher.api_key}")
            print(f"PublishID: {publish_id}")
            print("=" * 80)

    except Exception as e:
        print(f"\n[错误] 发布失败: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
